<template>
  <basic-container>
    <div class="title">
      <div class="name">印章管理</div>
      <div class="action-btn">
        <el-button type="primary" icon="Plus" @click="$router.push('/seal/public-seal-generate')">新增企业印章</el-button>
        <el-button type="primary" icon="Plus" @click="$router.push('/seal/private-seal-generate')">新增个人印章</el-button>
      </div>
    </div>
    <div class="card-bg">
      <el-tabs v-model="activeName" class="demo-tabs">
        <el-tab-pane label="创建的印章" name="first">
          <el-table
              :data="tableData"
              header-align="center">
            <el-table-column label="印章" align="center" min-width="160">
              <template #default="scope">
                <img :src="scope.row.sealPath" style="width: 150px">
              </template>
            </el-table-column>
            <el-table-column prop="sealName" label="印章名称" min-width="180" align="center"/>
            <el-table-column prop="sealId" label="印章编号" min-width="290" align="center"/>
            <el-table-column prop="sealStatus" label="状态" align="center" min-width="60">
              <template #default="scope">
                <div v-if="scope.row.sealStatus === 1">正常</div>
                <div v-else style="color: red">禁用</div>
              </template>
            </el-table-column>
            <el-table-column prop="sealUseNum" label="印章被使用次数" align="center" min-width="180">
              <template #default="scope">
                <el-tooltip content="点击查看使用详情" placement="top">
                  <el-button type="text" size="large" @click="getUseTable(scope.$index, scope.row)">{{scope.row.sealUseNum}}</el-button>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column prop="sealAuthorizeNum" label="授权数量" align="center">
              <template #default="scope">
                <el-tooltip content="点击查看授权详情" placement="top">
                  <el-button type="text" size="large" @click="getAuthTable(scope.$index, scope.row)">{{scope.row.sealAuthorizeNum}}</el-button>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="200px">
              <template #default="scope">
                <el-button type="text" size="small" @click="addSealAuth(scope.$index, scope.row)">新增授权</el-button>
                <el-button type="text" size="small" @click="getAuthTable(scope.$index, scope.row)">查看授权</el-button>
                <el-button type="text" size="small" @click="deleteSeal(scope.$index, scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
              :page-sizes="[5, 10, 15, 20]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="totalNum"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              align="center"
          >
          </el-pagination>
        </el-tab-pane>
        <el-tab-pane label="被授权的印章" name="second">
          <el-table
              :data="sealAuthTable"
              header-align="center">
            <el-table-column label="印章" align="center">
              <template #default="scope">
                <img :src="scope.row.sealPath" style="width: 140px">
              </template>
            </el-table-column>
            <el-table-column prop="sealName" label="印章名称" width="120" align="center"/>
            <el-table-column prop="sealId" label="印章编号" width="300px" align="center"/>
            <el-table-column prop="sealCreater" label="印章所有人" width="120px" align="center"/>
            <el-table-column prop="sealStatus" label="印章状态" align="center">
              <template #default="scope">
                <div v-if="scope.row.sealStatus === 1">正常</div>
                <div v-else style="color: red">禁用</div>
              </template>
            </el-table-column>
            <el-table-column prop="sealAuthorizeNum" label="授权时间" align="center">
              <template #default="scope">
                {{scope.row.sealAuth.authStartTime}}
                <div>至</div>
                {{scope.row.sealAuth.authEndTime}}
              </template>
            </el-table-column>
            <el-table-column prop="sealStatus" label="授权状态" align="center">
              <template #default="scope">
                <div v-if="scope.row.sealAuth.authStatus === 1">正常</div>
                <div v-else style="color: red">禁用</div>
              </template>
            </el-table-column>
            <el-table-column prop="diffDate" label="授权到期时间" align="center">
              <template #default="scope">
                <div v-if="scope.row.diffDate < 0" style="color: red">已到期</div>
                <div v-else-if="scope.row.diffDate > 0 && scope.row.diffDate < 10" style="color: red">仅剩{{scope.row.diffDate}}天</div>
                <div v-else>{{scope.row.diffDate}}天</div>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
              :page-sizes="[5, 10, 15, 20]"
              :page-size="authPageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="authTotalNum"
              @size-change="handleAuthSizeChange"
              @current-change="handleAuthCurrentChange"
              align="center"
          >
          </el-pagination>
        </el-tab-pane>
      </el-tabs>
    </div>


    <el-dialog v-model="dialogTableVisible" title="新增授权" width="600px" destroy-on-close>
      <el-form
          label-position='right'
          label-width="100px"
          ref="sealAuthFormRef"
          :model="sealAuthForm"
          :rules="sealAuthFormRules"
          size="large"
          >
        <el-form-item label="授权对象" prop="authSealUser">
          <div class="input">
            <el-autocomplete
                v-model="sealAuthForm.authSealUser"
                :fetch-suggestions="querySearchAsync"
                placeholder="请输入授权对象"
                @select="handleSelect"
            />
          </div>

        </el-form-item>
        <el-form-item label="授权角色" prop="authSealRole">
          <el-radio-group v-model="sealAuthForm.authSealRole">
            <el-radio label="1" >印章使用员</el-radio>
            <el-radio label="2" >印章审批员</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="授权范围" prop="authSealRange">
          <el-radio-group v-model="sealAuthForm.authSealRange">
            <el-radio label="1" >全部合同</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="有效期" prop="dateValue">
          <el-date-picker
              v-model="sealAuthForm.dateValue"
              type="daterange"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitAuth">确认</el-button>
          <el-button @click="dialogTableVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </basic-container>

</template>

<script setup>
import {ref,getCurrentInstance} from 'vue';
import {
  addSealAuthApi,
  delSealApi,
  getAuthSealApi,
  getAuthSealNumApi,
  getSealByCreaterApi,
  getSealNumApi,
} from '../../api/seal';
import {ElMessage, ElMessageBox} from 'element-plus';
import {getUserBySearchApi} from '../../api/user';
import {validatenull} from '../../utils/validate';
import {getDiffDate, getParenthesesStr, transformTime} from '../../utils/util';
import {useStore} from 'vuex';
const {proxy} = getCurrentInstance();

const activeName = ref("first")

/****************************** 我创建的印章 ******************************/

//分页代码
const totalNum = ref(0)
const currentPage=ref(1)
const pageSize=ref(5)

const handleCurrentChange = (currPage) => {
  currentPage.value = currPage
  getSealByCreater()
  window.scrollTo(0, 175);
}

const handleSizeChange = (val) => {
  pageSize.value=val
  getSealByCreater()
}

//我的印章的表格数据
const tableData = ref([])

const store = useStore()
const userId = store.getters.userId
/**
 * 获取我的印章数据
 */
const getSealByCreater = () => {
  getSealByCreaterApi(userId,currentPage.value,pageSize.value).then(res=>{
    tableData.value = res.data.result
  })
}
getSealByCreater()


/**
 * 获取我的印章数量
 */
const getSealNum = () => {
  getSealNumApi(userId).then(res=>{
    totalNum.value = res.data.result
  })
}
getSealNum()


/****************************** 被授权的印章 ******************************/

//分页代码
const authTotalNum = ref(0)
const authCurrentPage=ref(1)
const authPageSize=ref(5)

const handleAuthCurrentChange = (currPage) => {
  authCurrentPage.value = currPage
  getSealAuth()
  window.scrollTo(0, 175);
}

const handleAuthSizeChange = (val) => {
  authPageSize.value=val
  getSealAuth()
}

const sealAuthTable = ref([])

const getSealAuth = () => {
  getAuthSealApi(authCurrentPage.value,authPageSize.value,userId).then(res=>{
    let data = res.data.result
    for (let i = 0; i < data.length; i++){
      data[i].diffDate = getDiffDate(data[i].sealAuth.authEndTime)
      data[i].sealAuth.authStartTime = transformTime(data[i].sealAuth.authStartTime)
      data[i].sealAuth.authEndTime = transformTime(data[i].sealAuth.authEndTime)
    }
    sealAuthTable.value = data
  })
}
getSealAuth()

const getAuthSealNum = () => {
  getAuthSealNumApi(userId).then(res=>{
    authTotalNum.value = res.data.result
  })
}
getAuthSealNum()

//新增授权弹窗是否打开
const dialogTableVisible = ref(false)

const sealAuthFormRef = ref(null)
const sealAuthFormRules = ref({
  authSealUser: [ {required: true, message: "请输入授权对象",trigger: "change"} ],
  authSealRole: [ {required: true, message: '请选择授权角色', trigger: 'change'} ],
  authSealRange: [ {required: true, message: '请选择授权范围', trigger: 'change'} ],
  dateValue: [ {type: 'array',required: true, message: '请选择授权日期', trigger: 'change'} ]
})
/**
 * 印章授权表单
 * @type {Ref<UnwrapRef<{}>>}
 */
const sealAuthForm = ref({
  authSealId: '',
  authSealUser: '',
  authSealRole: '',
  authSealRange: '',
  authStartTime: '',
  authEndTime: '',
  authStatus: '',
  dateValue: []
})

/**
 * 根据用户输入实时获取数据库中的信息
 * @param queryString
 * @param callback
 */
const querySearchAsync = (queryString,callback) => {
  let list = [{}]
  if(!validatenull(queryString)){
    getUserBySearchApi(queryString).then(res=>{
      let data = res.data.result
      if(!validatenull(data)) {
        //在这里为这个数组中每一个对象加一个value字段, 因为autocomplete只识别value字段并在下拉列中显示
        for (let i of data) {
          i.value = i.userName + "(" + i.userId + ")";  //将想要展示的数据作为value
        }
        list = data;
      }else {
        data.value = "该用户不存在"
        list.push(data)
      }
      callback(list);
    })
  }
}

const handleSelect = (item) => {
 // console.log(sealAuthForm.value.authSealUser)
}

/**
 * 打开新增栏
 */
const addSealAuth = (index,row) => {
  dialogTableVisible.value = true
  sealAuthForm.value = {}
  sealAuthForm.value.authSealId = row.sealId
}
/**
 * 新增授权印章
 */
const submitAuth = () => {
  sealAuthFormRef.value.validate((valid)=>{
    if(valid){
      sealAuthForm.value.authStartTime = sealAuthForm.value.dateValue[0]
      sealAuthForm.value.authEndTime = sealAuthForm.value.dateValue[1]
      sealAuthForm.value.authSealUser = getParenthesesStr(sealAuthForm.value.authSealUser)
      addSealAuthApi(sealAuthForm.value).then(res=>{
        let data = res.data.result
        if(data === "success"){
          ElMessage.success("新增授权成功！")
          dialogTableVisible.value = false
          getSealByCreater()
          getSealNum()
        }else {
          ElMessage.error("新增授权失败，请重试!")
        }
      })
    }
  })
}

/**
 * 查看授权列表
 * @param index
 * @param row
 */
const getAuthTable = (index,row) => {
  proxy.$router.push({
    path:'/seal/seal-auth',
    query:{
      authSealId: row.sealId
    }
  })
}

/**
 * 查看使用列表
 * @param index
 * @param row
 */
const getUseTable = (index,row) => {
  proxy.$router.push({
    path:'/seal/seal-use-detail',
    query:{
      sealId: row.sealId
    }
  })
}

/**
 * 删除印章
 * @param index
 * @param row
 */
const deleteSeal = (index,row) => {
  ElMessageBox.confirm(
      '确认删除该印章吗?',
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        delSealApi(row.sealId).then(res=>{
          if(res.data.result === "success"){
            ElMessage({
              type: 'success',
              message: '删除成功',
            })
            getSealByCreater()
            getSealNum()
          }else {
            ElMessage({
              type: 'error',
              message: '删除失败，请重试',
            })
          }
        })

      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消删除',
        })
      })
}
</script>

<style scoped>
/deep/ .el-card__body {
  margin: 10px 20px;
}
/deep/ .el-tabs__item.is-active{
  color: #1063f1;
}
/deep/ .el-tabs__active-bar{
  background-color: #1063f1;
  margin-left: -20px;
  padding: 0 20px;
}
/deep/ .el-tabs__item.is-top:nth-child(2){
  padding-left: 20px;
}
/deep/ .el-tabs__item:hover{
  color: #1063f1;
}
/deep/ .el-tabs__nav-wrap::after {
  background-color: #e6e6e6;
}
.title{
  display: flex;
}
.name{
  font-size: 18px;
  width: 850px;
}
.action-btn{
  right: 60px ;
}
.card-bg{
  background-color: #fff;
  padding: 10px;
  margin-top: 10px;
}
/deep/ .el-button--primary{
  background-color: #1063f1;
  border-color: #1063f1;
}

/deep/ .el-button--text{
  color: #1063f1;
  font-weight: 500;
  font-family: 微雅软黑,Arial;
}

/deep/ .el-autocomplete {
    position: relative;
    display: inline-block;
    width: 350px;
}
.input{
  width: 400px;
}

/* 表格样式 */
/deep/ .el-table{
  margin-top: 10px;
}
/deep/ .el-table th{
  border-bottom: 1px solid #e8eaec !important;
}
/deep/ .el-table__header-wrapper th{
  background: #f8f8f9;
  color: #515a6e;
}

/deep/ .el-pagination{
  margin: 30px 0 0 0;
}
</style>
